package health_system.health_system.controller;

import health_system.health_system.dto.ApiResponse;
import health_system.health_system.dto.UserDTO;
import health_system.health_system.exception.UserNotFoundException;
import health_system.health_system.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/search")
@RequiredArgsConstructor
public class SearchController {

    private final UserService userService;

    /**
     * Search for users/friends
     * GET /api/search/friends?query={query}&type={type}
     *
     * @param query The search query
     * @param type The type of search (username, account_id, email, phone)
     * @return List of matching users
     */
    @GetMapping("/friends")
    public ResponseEntity<?> searchFriends(
            @RequestParam("query") String query,
            @RequestParam(value = "type", defaultValue = "username") String type) {
        
        log.info("Friend search request received - query: '{}', type: '{}'", query, type);
        
        List<UserDTO> results = Collections.emptyList();
        
        try {
            switch (type.toLowerCase()) {
                case "account_id":
//                    if (!query.matches("\\d+")) {
//                        log.warn("Invalid account_id format: '{}' - not a valid numeric ID", query);
//                        return ResponseEntity.ok(ApiResponse.success("Invalid account ID format. Account ID must be numeric.", Collections.emptyList()));
//                    }
                    
                    try {
//                        Long userId = Long.parseLong(query);
                        UserDTO user = userService.getUserByUsername(query);
                        results = Collections.singletonList(user);
                        log.info("Found user by account_id: {}", query);
                    } catch (UserNotFoundException e) {
                        log.info("No user found with account_id: {}", query);
                        // Return empty results for not found - don't throw exception
                    }
                    break;
                case "qrcode":
                    try {
                        UserDTO user = userService.getUserByUsername(query);
                        results = Collections.singletonList(user);
                        log.info("Found user by qrcode: {}", query);
                    } catch (UserNotFoundException e) {
                        log.info("No user found with qrcode: {}", query);
                    }
                    break;
                case "email":
                    try {
                        UserDTO user = userService.getUserByEmail(query);
                        results = Collections.singletonList(user);
                        log.info("Found user by email: {}", query);
                    } catch (UserNotFoundException e) {
                        log.info("No user found with email: {}", query);
                        // Return empty results for not found - don't throw exception
                    }
                    break;
                case "phone":
                    try {
                        UserDTO user = userService.getUserByPhoneNumber(query);
                        results = Collections.singletonList(user);
                        log.info("Found user by phone: {}", query);
                    } catch (UserNotFoundException e) {
                        log.info("No user found with phone: {}", query);
                    }
                    break;
                case "username":
                default:
                    results = userService.searchUsers(query);
                    log.info("Found {} users by username search: '{}'", results.size(), query);
                    break;
            }
            
            return ResponseEntity.ok(ApiResponse.success("Search completed successfully", results));
        } catch (Exception e) {
            log.error("Unexpected error searching for friends with query: '{}', type: '{}'", query, type, e);
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error(400, "Error searching for friends: " + e.getMessage()));
        }
    }
} 